package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"gomicrodemo/changgou-api-gateway/good/model"
	"gomicrodemo/common"
	pbGoods "gomicrodemo/proto/goods"
	"log"
)

func (g *Good_APIHandler) CreateSpu(c *gin.Context) {
	common.Print_RequestId(c)

	var (
		req     model.CreateSpuRequest
		rsp     *pbGoods.CreateSpuResponse
		err     error
		skuList []*pbGoods.Sku
	)

	err = c.ShouldBindJSON(&req)
	if err != nil {
		log.Printf("shoulebindjson fail, msg:%v", err.Error())
	}

	spu := &pbGoods.Spu{
		Sn:           req.Spu.Sn,
		Name:         req.Spu.Name,
		Caption:      req.Spu.Caption,
		BrandId:      req.Spu.BrandId,
		Category1Id:  req.Spu.Category1Id,
		Category2Id:  req.Spu.Category2Id,
		Category3Id:  req.Spu.Category3Id,
		TemplateId:   req.Spu.TemplateId,
		FreightId:    req.Spu.FreightId,
		Image:        req.Spu.Image,
		Images:       req.Spu.Images,
		SaleService:  req.Spu.SaleService,
		Introduction: req.Spu.Introduction,
		SpecItems:    convertToString(req.Spu.SpecItems),
		ParaItems:    convertToString(req.Spu.ParaItems),
		SaleNum:      req.Spu.SaleNum,
		CommentNum:   req.Spu.CommentNum,
		IsMarketable: req.Spu.IsMarketable,
		IsEnableSpec: req.Spu.IsEnableSpec,
		IsDelete:     req.Spu.IsDelete,
		Status:       req.Spu.Status,
	}

	for _, v := range req.SkuList {
		sku := &pbGoods.Sku{
			Sn:           v.Sn,
			Name:         v.Name,
			Price:        v.Price,
			Num:          v.Num,
			AlertNum:     v.AlertNum,
			Image:        v.Image,
			Images:       v.Images,
			Weight:       v.Weight,
			CreateTime:   v.CreateTime,
			UpdateTime:   v.UpdateTime,
			SpuId:        v.SpuId,
			CategoryId:   v.CategoryId,
			CategoryName: v.CategoryName,
			BrandName:    v.BrandName,
			Spec:         convertToString(v.Spec), //interface接收
			SaleNum:      v.SaleNum,
			CommentNum:   v.CommentNum,
			Status:       v.Status,
		}
		skuList = append(skuList, sku)
	}

	rsp, err = g.goodClient.CreateSpu(c, &pbGoods.CreateSpuRequest{
		Spu:     spu,
		SkuList: skuList,
	})
	if err != nil {
		log.Printf("CreateSpu fail, msg:%v", err.Error())
		c.JSON(200, gin.H{
			"Code": -1,
			"Msg":  err.Error(),
		})
		return
	}
	if rsp.Code != 0 {
		log.Printf("CreateSpu fail, msg:%v", rsp.Msg)
		c.JSON(200, gin.H{
			"Code": rsp.Code,
			"Msg":  rsp.Msg,
		})
		return
	}
	c.JSON(200, gin.H{
		"Code": rsp.Code,
		"Msg":  rsp.Msg,
	})
}

func convertToString(obj interface{}) string {
	byte, err := json.Marshal(obj)
	if err != nil {
		log.Printf("convertype fail, msg:%V", err.Error())
	}
	str := string(byte)
	return str
}
